
#import "AES128.h"
#import "CommonCrypto/CommonDigest.h"
#import "CommonCrypto/CommonCryptor.h"
@implementation AES128

+ (NSString*)AES128EncryptedFromString:(NSString *)value key:(NSString *)key
{
    NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
    NSData *en_data = [data AES128EncryptedDataWithKey:key];
    NSString *en_Value = [en_data hexUppercaseString];
    
    return en_Value;
}

+ (NSString*)AES128DecryptedFromString:(NSString *)value key:(NSString *)key
{
    NSData *enData = [[NSData alloc]initWithHexString:value];
    NSData *de_data = [enData AES128DecryptedDataWithKey:key];
    NSString *destr = [[NSString alloc] initWithData:de_data encoding:NSUTF8StringEncoding];
    return destr;
}

+ (NSString *)md5:(NSString *)inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

//md5 16位加密 （大写）
+ (NSString *)md5HexDigest:(NSString*)input
{
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, strlen(str), result);
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];//
    
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02X",result[i]];
    }
    return ret;
}


+ (NSData *)decryptData:(NSData *)data key:(NSData *)key iv:(NSData *)iv {
    // 检查密钥长度是否有效
    NSUInteger keyLength = [key length];
    if (keyLength != kCCKeySizeAES128 &&
        keyLength != kCCKeySizeAES192 &&
        keyLength != kCCKeySizeAES256) {
        NSLog(@"Invalid key size: %lu", (unsigned long)keyLength);
        return nil;
    }
    
    // 检查IV长度，CBC模式需要16字节
    if ([iv length] != kCCBlockSizeAES128) {
        NSLog(@"Invalid IV size: %lu", (unsigned long)[iv length]);
        return nil;
    }
    
    // 设置输出缓冲区
    size_t bufferSize = [data length] + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    // 执行解密
    size_t decryptedLength = 0;
    CCCryptorStatus status = CCCrypt(kCCDecrypt,
                                    kCCAlgorithmAES,
                                    kCCOptionPKCS7Padding,
                                    [key bytes],
                                    [key length],
                                    [iv bytes],
                                    [data bytes],
                                    [data length],
                                    buffer,
                                    bufferSize,
                                    &decryptedLength);
    
    NSData *decryptedData = nil;
    if (status == kCCSuccess) {
        decryptedData = [NSData dataWithBytes:buffer length:decryptedLength];
    } else {
        NSLog(@"Decryption failed with status: %d", status);
    }

    free(buffer);
    return decryptedData;
}

+ (NSString *)decryptString:(NSString *)string key:(NSString *)key iv:(NSString *)iv {
    // 将Base64编码的字符串转换为NSData
    NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0];
    if (!data) {
        NSLog(@"Invalid base64 string");
        return nil;
    }
    
    // 将key和iv转换为NSData
    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
    NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
    
    // 解密数据
    NSData *decryptedData = [self decryptData:data key:keyData iv:ivData];
    if (!decryptedData) {
        return nil;
    }
    
    // 将解密后的NSData转换为NSString
    return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSData *)dataWithMD5Hash:(NSData *)input {
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input.bytes, (CC_LONG)input.length, digest);
    
    NSData *output = [NSData dataWithBytes:digest length:CC_MD5_DIGEST_LENGTH];
    return output;
}

+ (NSString *)hexStringFromData:(NSData *)data {
    NSUInteger dataLength = data.length;
    NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
    const unsigned char *dataBuffer = (const unsigned char *)data.bytes;
    for (int i = 0; i < dataLength; ++i) {
        [hexString appendFormat:@"%02x", (unsigned int)dataBuffer[i]];
    }
    return [hexString copy];
}

+ (NSString *)getNowTimeStamp {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这一点对时间的处理很重要
    NSTimeZone*timeZone=[NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *dateNow = [NSDate date];
    NSString *timeStamp = [NSString stringWithFormat:@"%ld", (long)[dateNow timeIntervalSince1970]];
    return timeStamp;

}


@end
